package com.yuntian.controller;

import com.yuntian.dto.NyuukoForm;
import com.yuntian.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/PR30201")
public class NyuukoController {

    @Autowired
    private ProductService productService;

    // 处理GET请求：初始化页面
    @GetMapping
    public String initPage(Model model) {
        // 初始化空表单
        model.addAttribute("nyuukoForm", new NyuukoForm());
        model.addAttribute("loginUser", "張毅");
        model.addAttribute("error", null); // 清除错误提示
        return "PR30201";
    }

    // 处理POST请求：表单提交（查询/更新）
    @PostMapping
    public String handleSubmit(NyuukoForm form, Model model) {
        model.addAttribute("error", null);
        model.addAttribute("message", null);

        try {
            if ("検索".equals(form.getSubmit())) {
                // 执行查询
                form = productService.queryProduct(form);
            } else if ("更新".equals(form.getSubmit())) {
                // 执行更新
                form = productService.updateStock(form);
                model.addAttribute("message", "入庫完了：新在庫数=" + form.getNyuukoatoSuu());
            }
        } catch (IllegalArgumentException e) {
            model.addAttribute("error", e.getMessage());
        } catch (Exception e) {
            model.addAttribute("error", "エラー：" + e.getMessage());
        }

        model.addAttribute("nyuukoForm", form);
        model.addAttribute("loginUser", "張毅");
        return "PR30201";
    }
}